package com.ccrego.haiyi.account.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.ccrego.haiyi.R;
import com.ccrego.haiyi.account.Account;
import com.ccrego.haiyi.account.AccountManager;
import com.ccrego.haiyi.account.ParamKey;
import com.ccrego.haiyi.account.UrlCenter;
import com.ccrego.haiyi.app.MainActivity;
import com.ccrego.haiyi.common.http.MyHttpRequest;
import com.ccrego.haiyi.common.http.TokenInfo;
import com.ccrego.haiyi.utils.FragmentUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.RegularUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;

public class WxBindActivity extends BaseActivity {
    private static final int CATPCHA_TYPE_BIND = 1;

    private MyCountDownTimer mc;
    String info;
    @Bind(R.id.itetBindPhone)
    EditText mItetBindPhone;
    @Bind(R.id.itetBindCode)
    EditText mItetBindCode;
    @Bind(R.id.getBindCode)
    TextView mGetBindCode;
    private String openid;
    private String nickname;
    private String province;
    private int sex;
    private String city;
    private String headimgurl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolsBar();
        info = getIntent().getStringExtra("info");
        EasyToast.showToast(getApplicationContext(), "暂未绑定手机号码");
    }


    public String getBindPhone() {
        return mItetBindPhone.getText().toString().trim();
    }

    public String getBindCode() {
        return mItetBindCode.getText().toString().trim();
    }

    private void initToolsBar() {
        setTitle("微信登录");
        getCustomToolbar().addLeftImageButton(R.mipmap.icon_back1, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mc != null) {
                    mc.cancel();
                }
                finish();
            }
        });
    }

    public static void start(Activity activity, String info) {
        Intent intent = new Intent(activity, WxBindActivity.class);
        intent.putExtra("info", info);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_wx_bind, null);
    }

    @OnClick({R.id.getBindCode, R.id.btn_bind_regist})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.getBindCode:
                if (TextUtils.isEmpty(getBindPhone())) {
                    FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
                    return;
                } else if (!RegularUtils.isMobileSimple(getBindPhone())) {
                    FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
                    return;
                }
                //发送验证码
                sendMessage();
                break;
            case R.id.btn_bind_regist:
                //绑定手机
                if (TextUtils.isEmpty(getBindPhone())) {
                    FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
                    return;
                } else if (!RegularUtils.isMobileSimple(getBindPhone())) {
                    FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
                    return;
                }else if (TextUtils.isEmpty(getBindCode())) {
                    FragmentUtils.showWarnDialog("请输入验证码", getSupportFragmentManager());
                    return;
                }
              //先验证验证码
                isCodeExist();

                break;
        }
    }

    private void isCodeExist() {
        HttpRequest request = new HttpRequest(getBaseContext());
        String UrlIsExist = String.format(UrlCenter.ISCodeExist, getBindPhone(), CATPCHA_TYPE_BIND, getBindCode());
        request.get(UrlIsExist, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }
            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                try {
                    JSONObject joj = new JSONObject(o);
                    String error = joj.getString("error");
                    if(error.equals("验证码错误")==true){
                        EasyToast.showToast(getApplicationContext(),"验证码错误");
                    }else{
                        putMessage();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    //绑定手机
    private void putMessage() {
        try {
            Log.e("infoinfo",info);
            JSONObject joj = new JSONObject(info);
            openid = joj.getString("openid");
            nickname = joj.getString("nickname");
            sex = joj.getInt("sex");
            province = joj.getString("province");
            city = joj.getString("city");
            headimgurl = joj.getString("headimgurl");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpRequest request = new HttpRequest(WxBindActivity.this);
        JSONObject jobj = new JSONObject();
        try {
            jobj.put(ParamKey.PHONE, getBindPhone());
            jobj.put(ParamKey.OPENID, openid);
            jobj.put(ParamKey.CAPTCHA, getBindCode());
            jobj.put(ParamKey.NICKNAME, nickname);
            jobj.put(ParamKey.PROVINCE, province);
            jobj.put(ParamKey.SEX, sex);
            jobj.put(ParamKey.CITY, city);
            jobj.put(ParamKey.HEADIMGURL, headimgurl);
            Log.e("ParamKey",getBindPhone());
            Log.e("ParamKey",openid);
            Log.e("ParamKey",getBindCode());
            Log.e("ParamKey",nickname);
            Log.e("ParamKey",province);
            Log.e("ParamKey",sex+"");
            Log.e("ParamKey",city);
            Log.e("ParamKey",headimgurl);
            request.post(UrlCenter.WX_REGISTER, jobj, new DataRequestListener<TokenInfo>(TokenInfo.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
                @Override
                public void onSuccess(TokenInfo tokenInfo) {
                    super.onSuccess(tokenInfo);
                    AccountManager.updateTokenInfo(tokenInfo);
                    setAccount(tokenInfo);
                }
                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(WxBindActivity.this,strMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setAccount(final TokenInfo tokenInfo) {
        IHttpRequest request = new MyHttpRequest(this);
        request.get(UrlCenter.USER, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onSuccess(Account account) {
                account.setPhone(getBindPhone());
                AccountManager.setCurrentAccount(account);

                EasyToast.showToast(getBaseContext(), "登录成功");
                MainActivity.start(WxBindActivity.this);
                finish();
            }

            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                EasyToast.showToast(WxBindActivity.this,strMsg);
            }
        });

    }

    private void sendMessage() {
        HttpRequest request = new HttpRequest(this);
        JSONObject jobj = new JSONObject();
        String UrlCaptcha = String.format(UrlCenter.CAPTCHA, getBindPhone(), CATPCHA_TYPE_BIND);
        try {
            jobj.put(ParamKey.PHONE, getBindPhone());
            jobj.put(ParamKey.TYPE, CATPCHA_TYPE_BIND);
            request.post(UrlCaptcha, jobj, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }
                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    EasyToast.showToast(WxBindActivity.this, "发送验证码成功!");
                    mGetBindCode.setClickable(false);
                    mc = new MyCountDownTimer(60000, 1000);
                    mc.start();
                }
                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //返回键设置
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mc != null) {
                mc.cancel();
            }
            finish();
        }
        return true;
    }

    /**
     * 继承 CountDownTimer 防范
     * <p>
     * 重写 父类的方法 onTick() 、 onFinish()
     */
    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          <p>
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          <p>
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mGetBindCode.setText("重新获取");
            if (!TextUtils.isEmpty(mGetBindCode.getText())) {
                mGetBindCode.setClickable(true);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mGetBindCode != null) {
                mGetBindCode.setText(millisUntilFinished / 1000 + "s");
            }
        }
    }
}
